package com.theme.passport.controller.app;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.theme.common.base.DateHandler;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.view.R;
import com.theme.common.office.dom4j.Dom4jHandler;
import com.theme.passport.annotation.Login;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.dao.CustomMapper;
import com.theme.passport.entity.constant.*;
import com.theme.passport.entity.theme.AlbumProductEntity;
import com.theme.passport.entity.theme.RecommendProductEntity;
import com.theme.passport.entity.theme.ThemeAttachmentEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.service.theme.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *@name:OtherThemeController<tb>
 *@title:主题其他接口<tb>
 *@author:cuixinfu@51play.com<tb>
 *@date:2021/10/22 8:59:41<tb>
 */
@RestController
@RequestMapping("app/other-theme")
@Api("其他主题相关接口[精品主题(Banner),最新主题,今日推荐主题,热门主题]")
public class OtherThemeController extends AbstractController {
    @Autowired
    private ThemeService themeService;
    @Autowired
    private CarouselService carouselService;

    @Autowired
    private DownloadHistoryService downloadHistoryService;
    @Autowired
    private ThemeAttachmentService attachmentService;
    @Autowired
    private AlbumProductService albumProductService;
    @Autowired
    private RecommendProductService recommendProductService;
    @Autowired
    private CustomMapper mapper;

    @Value("${theme.generate.path}")
    private String generateThemePath;


    @GetMapping("banner")
    @ApiOperation("获取轮播图主题(Banner)")
    public R banner(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("limit", limit);
        params.put("type", String.valueOf(CarouselTypeEnum.THEME.getValue()));
        PageUtils pages = carouselService.queryPage(params);
        return R.ok().put("page", pages);
    }

    @GetMapping("newest")
    @ApiOperation("获取最新主题[时间排序]")
    public R newest(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = themeService.queryPage(params);
        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }

    @GetMapping("newProduct")
    @ApiOperation("获取新品主题[时间排序]")
    public R newProduct(@RequestParam(value = "page", defaultValue = "1") String page,
                    @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("nts", String.valueOf(ThemeNtsEnum.YES.getValue()));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = themeService.queryPage(params);
        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }


    @GetMapping("todayRecommend")
    @ApiOperation("获取今日推荐主题")
    public R todayRecommend(@RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("type", AubumTypeEnum.THEME.getValue())
                .eq("recommend_id", 1);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null){
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.THEME.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> themeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend ->{
            themeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages =themeService.queryThemeByIds(params,themeIds);

        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }

    @GetMapping("recommend")
    @ApiOperation("获取推荐主题")
    public R recommend(@RequestParam(value = "recommendId") Long recommendId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        List<RecommendProductEntity> recommendList = null;
        Wrapper<RecommendProductEntity> queryWrapper = new QueryWrapper<RecommendProductEntity>()
                .eq("recommend_id", recommendId);
        recommendList = recommendProductService.list(queryWrapper);
        if (recommendList == null){
            queryWrapper = new QueryWrapper<RecommendProductEntity>()
                    .eq("type", AubumTypeEnum.THEME.getValue());
            recommendList = recommendProductService.list(queryWrapper);
        }

        List<Long> themeIds = new ArrayList<>(16);
        recommendList.forEach(themeRecommend ->{
            themeIds.add(themeRecommend.getObjectId());
        });
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages =themeService.queryThemeByIds(params,themeIds);

        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }

    @GetMapping("album")
    @ApiOperation("获取主题专题列表")
    public R albumList(@RequestParam(value = "albumId") Long albumId,
                       @RequestParam(value = "page", defaultValue = "1") String page,
                       @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Wrapper<AlbumProductEntity> queryWrapper = new QueryWrapper<AlbumProductEntity>()
                .eq("album_id", albumId);
        List<AlbumProductEntity> albumProductList = albumProductService.list(queryWrapper);
        List<Long> themeIds = new ArrayList<>(16);
        albumProductList.forEach(albumProduct ->{
            themeIds.add(albumProduct.getObjectId());
        });

        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages =themeService.queryThemeByIds(params,themeIds);

        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }

    @GetMapping("hot")
    @ApiOperation("获取热门主题[前七天下载量最高的]")
    public R hot(@RequestParam(value = "page", defaultValue = "1") String page,
                 @RequestParam(value = "limit", defaultValue = "10") String limit) {
        //1、根据时间查询昨天24小时（一天）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = DateHandler.addDateDays(new Date(),-7);
        Date endDate = DateHandler.addDateDays(new Date(),-1);
        Date startTime = DateHandler.getStartTime(startDate);
        Date endTime = DateHandler.getEndTime(endDate);
        Map<String, Object> hotParams = new HashMap<>();
        hotParams.put("type",  String.valueOf(DownloadTypeEnum.THEME.getValue()));
        hotParams.put("startTime", formatter.format(startTime));
        hotParams.put("endTime", formatter.format(endTime));
        //2、得的主题id
        List<Long> themeIds = downloadHistoryService.queryHotDownloadIds(hotParams);
        //3、根据主题id查询
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        //没有最新下的话数据正常显示几个
        if (themeIds == null){
            PageUtils pages =themeService.queryPage(params);
            List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
            pages.setList(newThemeList);
            return R.ok().put("page", pages);
        }
        PageUtils pages =themeService.queryThemeByIds(params,themeIds);
        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }

    @GetMapping("hotBak")
    @ApiOperation("获取热门主题[前一天下载量最高的]")
    public R hotBak(@RequestParam(value = "page", defaultValue = "1") String page,
                 @RequestParam(value = "limit", defaultValue = "10") String limit) {
        //1、根据时间查询昨天24小时（一天）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = DateHandler.addDateDays(new Date(),-1);
        Date startTime = DateHandler.getStartTime(newDate);
        Date endTime = DateHandler.getEndTime(newDate);
        Map<String, Object> hotParams = new HashMap<>();
        hotParams.put("type", String.valueOf(DownloadTypeEnum.THEME.getValue()));
        hotParams.put("startTime", formatter.format(startTime));
        hotParams.put("endTime", formatter.format(endTime));
        //2、得的主题id
        List<Long> themeIds = downloadHistoryService.queryHotDownloadIds(hotParams);
        //3、根据主题id查询
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("status", String.valueOf(status));
        params.put("page", page);
        params.put("limit", limit);
        //没有最新下的话数据正常显示几个
        if (themeIds == null){
            PageUtils pages =themeService.queryPage(params);
            List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
            pages.setList(newThemeList);
            return R.ok().put("page", pages);
        }
        PageUtils pages =themeService.queryThemeByIds(params,themeIds);
        List<ThemeEntity> newThemeList = getNewThemeList((List<ThemeEntity>) pages.getList(), attachmentService);
        pages.setList(newThemeList);
        return R.ok().put("page", pages);
    }


    /**TODO 2022年1月25日
     * @title: 1、根据主题规则生成xml文件
     *         2、转换文件流(InputStream)上传阿里云oss <tb>
     *         3、返回阿里云OSS下载地址url <tb>
     * @params: sing_B9D8026A-D2AE-462B-BFFE-A3E0C95DE4B1.mobileConfig文件名称  <tb>
     * @author: cuixinfu@51play.com <tb>
     * @date: 2022/1/25 9:44:24<tb>
     */
    @Login
    @GetMapping("/generateDescribeFile")
    @ApiOperation("用户下载主题生成描述文件返回[废弃]")
    public R generateDescribeFile(HttpServletResponse response,
                                  @RequestParam("themeId") Long themeId,
                                  @RequestParam(value = "fileName") String fileName) throws Exception {
        ThemeEntity theme = themeService.getById(themeId);
        if (!theme.getStatus().equals(ThemeStatusEnum.NORMAL.getValue())) {
            return R.error("该主题不存在或已下架!!!").put("theme", theme);
        }
        response.setContentType("octets/stream");
        response.setContentType("text/xml;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xml");
        ServletOutputStream outStream = response.getOutputStream();

        // 生成xml文件
        Dom4jHandler dom4jHandler = new Dom4jHandler();
        //String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String filePath = generateThemePath + File.separator + fileName + ".xml";
        File file = new File(filePath);
        //判断该文件是否下载过，如已存在忽略，不存在则创建文件
        if(!file.exists()) {
            try {
                dom4jHandler.creatXml(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // 输出文件流
            InputStream inputStream = new FileInputStream(file);
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1){
                b = inputStream.read(buffer);
                outStream.write(buffer,0,b);
            }

            inputStream.close();
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("syncThemeImages")
    @ApiOperation("同步更新之前数据，似乎无用")
    public R syncThemeImages() {
        List<ThemeEntity> themeList = themeService.list();
        themeList.forEach(theme ->{
            List<ThemeAttachmentEntity> listAttachment = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                ThemeAttachmentEntity attachment = new ThemeAttachmentEntity();
                attachment.setObjectId(theme.getId());
                attachment.setType(ThemeAttchmentTypeEnum.THEME.getValue());
                attachment.setCreated(new Date());
                if (i == 0){
                    attachment.setFileUrl("image1");
                }
                if (i == 0){
                    attachment.setFileUrl("image2");
                }
                if (i == 0){
                    attachment.setFileUrl("image3");
                }
                listAttachment.add(attachment);
            }
            attachmentService.saveBatch(listAttachment);
        });
        return R.ok();
    }

    public  List<ThemeEntity> getNewThemeList(List<ThemeEntity> themeList, ThemeAttachmentService attachmentService){
        themeList.forEach(theme ->{
            //SysUserEntity byId = sysUserService.getById(theme.getUserId());
            //theme.setUseNickname(byId.getNickname());
            //主题标签
            String label = theme.getLabel();
            if (label != null){
                String[] split = label.split(",");
                theme.setLabels(Arrays.asList(split));
            }
            //主题预览图：
            QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
            fileNameWrapper.and(wrapper -> wrapper
                    .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                    .eq("object_id", theme.getId()));
            List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
            List<String> images = new ArrayList<>();
            attachmentList.forEach(attachment -> {
                images.add(attachment.getFileUrl());
            });
            theme.setImages(images);
            theme.setXzl(mapper.getOneInteger("select count(id) from tab_download_history where object_id  = "+theme.getId()+" and  type = 1"));
        });
        return themeList;
    }

}
